//
//  TZWOauthViewController.swift
//  Sinaweibotzw
//
//  Created by 檀志文 on 16/4/11.
//  Copyright © 2016年 ios檀志文. All rights reserved.
//

import UIKit

import SVProgressHUD

class TZWOauthViewController: UIViewController {

    override func loadView() {
        view = webView
    
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //设置背景颜色
        view.backgroundColor = GlobalColor
        
        //设置导航栏左右两边的按钮
        setupNavigationBar()
        
        HMPrint("oauthUrl: \(oauthURL())")
        //加载授权界面
        let url = oauthURL()
        let request = NSURLRequest(URL: url)
        webView.loadRequest(request)
        SVProgressHUD.showWithStatus("正在加载登录界面...")
        SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.None)
    
    }
    //拼接授权界面
    private func oauthURL() -> NSURL {
    let urlString = OauthUrl + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri
        return NSURL(string: urlString)!
    }
    
   private func setupNavigationBar(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("autoFill"))
    
    
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: Selector("close"))
    }
    
   @objc private func autoFill(){
    
    let js = "document.getElementById('userId').value = '13559211170';document.getElementById('passwd').value = '303303'"
    webView.stringByEvaluatingJavaScriptFromString(js)
    }
    
    @objc private func close(){
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // MARK: 懒加载
    private lazy var webView: UIWebView = UIWebView()
}

extension TZWOauthViewController : UIWebViewDelegate{
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL?.absoluteString
        
//        HMPrint("webView是否要去加载一个请求: \(urlString)")
        
        let isRedirectUrl = urlString!.hasPrefix(redirect_uri)
        if !isRedirectUrl{
            return true
        }else{
            let query = request.URL?.query
            HMPrint("query: \(query)")
            let codeString = "code="
            if query!.hasPrefix(codeString){
                HMPrint("授权按钮点击了:\(query)")
                let code = (query! as NSString).substringFromIndex(codeString.characters.count)
                HMPrint("code: \(code)")
                
                //使用AFN发送POST,获取access_token,当使用POST获取AccessToken成功后下次输入密码不会弹出授权按钮，会直接去获取AccessToken,如果想看到授权按钮需要去取消授权
//                loadAccessToken(code)
                TZWUserAccoutViewModel.sharedInstance.loadAccessToken(code, loadAccessTokenCallBack: { (error) -> () in
                    if error != nil {
                    SVProgressHUD.showErrorWithStatus("网络不给力")
                    // 延时关闭
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                        self.close()
                    })
                    return
                }
                    HMPrint("加载AccessToken成功了")
                        self.close()
                    
//                    跳转到欢迎界面
                    let controller = TZWWelComeViewController()
                    (UIApplication.sharedApplication().delegate as! AppDelegate).switchViewController(controller)
                    })
            }  else {
                HMPrint("取消按钮点击了")
//                关闭控制器
                
                close()
            }
            return false
        }
    }
    /**
    *  webview 加载完成
    */
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    /**
    *  webview 加载失败
    */
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        HMPrint("error: \(error)")
        if error?.code == 102 {
            return
        }
        
        SVProgressHUD.showErrorWithStatus("网络不给力...")
        SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.None)
    }
    
}










